package com.hls.mvc.core;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class PackageUtil {
    /**
     * get the all classes under the certain package(including sub packages)
     * @param packageName package name
     * @param childPackage is iterate sub packages
     * @return full class name
     * @throws Exception 
     */ 
    public static List<String> getClassName(String packageName, boolean childPackage) throws Exception { 
        List<String> fileNames = null; 
        ClassLoader loader = Thread.currentThread().getContextClassLoader(); 
        String packagePath = packageName.replace(".", "/"); 
        URL url = loader.getResource(packagePath); 
        if (url != null) { 
            String type = url.getProtocol(); 
            if ("file".equals(type)) { 
                fileNames = getClassNameByFile(url.getPath(), null, childPackage); 
            } else if (("jar").equals(type)) { 
                fileNames = getClassNameByJar(url.getPath(), childPackage); 
            } 
        } else { 
            fileNames = getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage); 
        } 
        return fileNames; 
    } 
 
    /**
     *  get the all classes under the certain package
     * @param filePath file path
     * @param className collection of classes
     * @param childPackage is iterate sub packages
     * @return full name of the class
     */ 
    private static List<String> getClassNameByFile(String filePath, List<String> className, boolean childPackage) { 
        List<String> myClassName = new ArrayList<String>(); 
        File file = new File(filePath); 
        File[] childFiles = file.listFiles(); 
        for (File childFile : childFiles) { 
            if (childFile.isDirectory()) { 
                if (childPackage) { 
                    myClassName.addAll(getClassNameByFile(childFile.getPath(), myClassName, childPackage)); 
                } 
            } else { 
                String childFilePath = childFile.getPath(); 
                if (childFilePath.endsWith(".class")) { 
                    childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf(".")); 
                    childFilePath = childFilePath.replace("\\", "."); 
                    myClassName.add(childFilePath); 
                } 
            } 
        } 
 
        return myClassName; 
    }
    /**
     * get the all classes under jar file.
     * @param jarPath jar file path
     * @param childPackage is iterate sub packages
     * @return the full name of the class
     * @throws Exception 
     */ 
    private static List<String> getClassNameByJar(String jarPath, boolean childPackage) throws Exception { 
        List<String> myClassName = new ArrayList<String>(); 
        String[] jarInfo = jarPath.split("!"); 
        String jarFilePath = jarInfo[0].substring(jarInfo[0].indexOf("/")); 
        String packagePath = jarInfo[1].substring(1);
        JarFile jarFile = null;
        try { 
            jarFile = new JarFile(jarFilePath); 
            Enumeration<JarEntry> entrys = jarFile.entries(); 
            while (entrys.hasMoreElements()) { 
                JarEntry jarEntry = entrys.nextElement(); 
                String entryName = jarEntry.getName(); 
                if (entryName.endsWith(".class")) { 
                    if (childPackage) { 
                        if (entryName.startsWith(packagePath)) { 
                            entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf(".")); 
                            myClassName.add(entryName); 
                        } 
                    } else { 
                        int index = entryName.lastIndexOf("/"); 
                        String myPackagePath; 
                        if (index != -1) { 
                            myPackagePath = entryName.substring(0, index); 
                        } else { 
                            myPackagePath = entryName; 
                        } 
                        if (myPackagePath.equals(packagePath)) { 
                            entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf(".")); 
                            myClassName.add(entryName); 
                        } 
                    } 
                } 
            } 
        } catch (Exception e) { 
            throw e; 
        }finally{
            if(null != jarFile){
                jarFile.close();
            }
        } 
        return myClassName; 
    } 
 
    /**
     * search certain jar file from all jars
     * @param urls URL collection
     * @param packagePath the path of the package
     * @param childPackage is iterate sub packages
     * @return the full name of the class
     * @throws Exception 
     */ 
    private static List<String> getClassNameByJars(URL[] urls, String packagePath, boolean childPackage) throws Exception { 
        List<String> myClassName = new ArrayList<String>(); 
        if (urls != null) { 
            for (int i = 0; i < urls.length; i++) { 
                URL url = urls[i]; 
                String urlPath = url.getPath(); 
                // exclude classes path
                if (urlPath.endsWith("classes/")) { 
                    continue; 
                } 
                String jarPath = urlPath + "!/" + packagePath; 
                myClassName.addAll(getClassNameByJar(jarPath, childPackage)); 
            } 
        } 
        return myClassName; 
    }
}
